// API 接口封装
const BASE_URL = process.env.NODE_ENV === 'development' 
  ? 'http://localhost:3000/api' 
  : 'https://your-domain.com/api'

// 请求拦截器
const request = (options) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        ...options.header
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          reject(res)
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 获取列表数据
export const getListData = (params) => {
  return request({
    url: '/list',
    method: 'GET',
    data: params
  })
}

// 获取用户信息
export const getUserInfo = () => {
  return request({
    url: '/user/info',
    method: 'GET'
  })
}

// 更新用户信息
export const updateUserInfo = (data) => {
  return request({
    url: '/user/update',
    method: 'POST',
    data
  })
}

// 获取配置信息
export const getConfig = () => {
  return request({
    url: '/config',
    method: 'GET'
  })
}

// 上传文件
export const uploadFile = (filePath, formData = {}) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: BASE_URL + '/upload',
      filePath,
      name: 'file',
      formData,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(JSON.parse(res.data))
        } else {
          reject(res)
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 通用错误处理
export const handleError = (error) => {
  console.error('API Error:', error)
  
  let message = '网络错误，请稍后重试'
  
  if (error.statusCode) {
    switch (error.statusCode) {
      case 400:
        message = '请求参数错误'
        break
      case 401:
        message = '未授权，请重新登录'
        break
      case 403:
        message = '没有权限'
        break
      case 404:
        message = '请求的资源不存在'
        break
      case 500:
        message = '服务器内部错误'
        break
      default:
        message = `请求失败 (${error.statusCode})`
    }
  }
  
  uni.showToast({
    title: message,
    icon: 'none',
    duration: 2000
  })
  
  return Promise.reject(error)
}
